package com.goockr.createqrcodedemo;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView iv_QRCode=(ImageView) findViewById(R.id.iv_QRCode);
        Button bt_CreateQRCode=(Button) findViewById(R.id.bt_CreateQRCode);
        bt_CreateQRCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //二维码图片较大时，生成图片、保存文件的时间可能较长，因此放在新线程中
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final String filePath = getFileRoot(MainActivity.this) + File.separator
                                + "qr_" + System.currentTimeMillis() + ".jpg";
                        boolean success = QRCodeUtil.createQRImage("jetgege", 800, 800,null, filePath);

                        if (success) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    iv_QRCode.setImageBitmap(BitmapFactory.decodeFile(filePath));
                                }
                            });
                        }
                    }
                }).start();
            }
        });
    }

    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return context.getFilesDir().getAbsolutePath();
    }
}
